import React, { Component } from 'react'
import { Card,Button, Checkbox, Form, Input, message } from 'antd'

import logo from 'assets/logo.png'
import style from './login.module.scss'
import { login } from 'api/user'
import { setToken } from 'utils/storage'

export class Login extends Component {
    state = {
        loading: false
    }
    render() {
        return (
        <div className={style.login}>
            <Card className='login-container'>
                <img className='login-logo' src={logo} alt="" />
                <Form autoComplete="off"  size='large' onFinish={this.LoginRef} initialValues={{mobile:'13911111111',code:'246810',agree:true}}>
                    <Form.Item name='mobile' validateTrigger='onBlur' rules={[{
                        required:true,
                        message:'手机号不能为空'
                    },{
                        pattern:/^1[3-9]\d{9}$/,
                        message:'手机号格式不正确',
                    }]}>
                        <Input autoComplete='fales' placeholder='请输入手机号'/>
                    </Form.Item>
                    <Form.Item name='code' validateTrigger='onBlur' rules={[{
                        required:true,
                        message:'验证码不能为空'
                    },{
                        len:6,
                        message:'验证码为6个字符'
                    }]}>
                        <Input autoComplete='fales' placeholder='请输入验证码'/>
                    </Form.Item>
                    <Form.Item name='agree' valuePropName='checked' rules={[{
                        validator:(rule, value) => value ? Promise.resolve() : Promise.reject(new Error('请阅读并同意协议'))
                    }]}>
                        <Checkbox>我已阅读并同意[用户服务协议]和[隐私政策]</Checkbox>
                    </Form.Item>
                    <Form.Item>
                        <Button block loading={this.state.loading} type="primary" htmlType="submit"> 登录 </Button>
                    </Form.Item>
                </Form>
            </Card>
        </div>
        )
    }

    LoginRef = async ({mobile,code}) => {
        this.setState({
            loading:true
        })
        try {
            const res = await login({mobile,code})
            message.success('登录成功',0.8,()=>{
                setToken(res.data.token)
                // console.log('login',this.props)
                const {state} = this.props.location
                // console.log('login',state)
                if(state) {
                    this.props.history.push(state.from)
                } else {
                    this.props.history.push('/home')
                }
            })
        } catch(error) {
            console.dir(error)
            message.warning(error.response.data.message,1,()=>{
                this.setState({
                    loading:false
                })
            })
        }
    }
}

export default Login